package com.hd.trans.network.component

import com.hd.trans.network.ApiServiceManager
import com.hd.trans.network.ParamJson.LanguageParam
import com.hd.trans.network.RxSchedulers
import com.hd.trans.network.bean.LanguageCodeResponse
import com.hd.trans.ui.service.NetDisposableObserver
import java.util.Timer
import java.util.TimerTask

/**
 * 语种识别：华为机器人服务 + V4 接口，二选一
 * implementation 'com.huawei.hms:ml-computer-language-detection:3.6.0.312'
 */
object LangDetectComponent {
    const val UNKNOWN = "unknown"
    private var timer: Timer? = null
    private var lastTimeMillis: Long = 0L

    private fun limitExecution(input: String, engine: Int = 1, callback: (String)->Void?){
        val currentTimeMillis = System.currentTimeMillis()
        if(currentTimeMillis - lastTimeMillis < 1000) {
            timer?.cancel()
            timer = Timer()
            timer?.schedule(object : TimerTask() {
                override fun run() {
                    doLangDetect(input, engine, callback)
                }
            }, 1000) //500毫秒后执行TimeTask的run方法
        }else{
            doLangDetect(input, engine, callback)
        }
        lastTimeMillis = currentTimeMillis
    }
    private fun doLangDetect(input: String, engine: Int = 1, callback: (String)->Void?) {
        if(input.isEmpty()){
            callback?.invoke(UNKNOWN)
            return
        }
        val text = if(input.length > 1000){//限制1000字符
            input.substring(0, 1000)
        }else{
            input
        }
        //V4接口
        getLanguageCode(text, callback)
    }

    private fun getLanguageCode(input: String, callback: ((String)->Void?)) {
        ApiServiceManager.apiService
            .getLanguageCode(LanguageParam(input))
            .compose(RxSchedulers.applySchedulers())
            .subscribe(NetDisposableObserver(object :
                NetDisposableObserver.NetCallBack<LanguageCodeResponse?> {
                override fun onResponse(response: LanguageCodeResponse?) {
                    if (response != null) {
                        callback.invoke(response.getcode?: UNKNOWN)
                    }
                }

                override fun onError(code: Int, msg: String) {
                    callback.invoke(UNKNOWN)
                }

                override fun onTokenInvalid(msg: String) {
                    callback.invoke(UNKNOWN)
                }
            }))
    }

    fun firstLangDetect(input: String, callback: (String)->Void?) {
        limitExecution(input, 1, callback)
    }

    fun firstLangDetect(input: String, engine: Int = 1, callback: (String)->Void?) {
        limitExecution(input, engine, callback)
    }

    fun stopDetector(){
    }

}